// packageA/pages/consumableList/consumableList.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:{},
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //搜索关键词
    searchValue:'',
    //删除确认框
    showDelete:false,
    //删除的id
    deleteId:null,
    //状态筛选
    optionState:[
      {text: '所有状态', value: -1},
      {text: '未接待', value: 0},
      {text: '已接待', value: 2},
      {text: '已完成', value: 1}
    ],
    valueState: -1,
    //接单人筛选
    optionReceive:[
      {text: '我接单的', value: 1},
      {text: '所有记录', value: 2},
    ],
    valueReceive: null,
    //当前登录用户
    user:null,
    //用户权限
    authority:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let user=app.globalData.userInfo;
    let authority=app.globalData.authority;

    this.setData({
      user: user,
      authority: authority
    })

    //设置valueReceive（平台售后人员查自己接单的，其他查所有）
    if(authority.iot.afterSales && authority.iot.afterSales.afterBtn){
      this.setData({
        valueReceive: 1
      })
    }else{
      this.setData({
        valueReceive: 2
      })
    }

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);

      console.log('耗材工单传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })
    }

    //获取列表数据
    this.getList();

    this.setData({
      authority:app.globalData.authority
    })
  },

  //获取列表数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let dataObj={
      selectFields: ['id', 'orderNo', 'equipmentNo', 'depart', 'project', 'categories', 'part', 'repairMan','repairDate', 'receiver', 'receiverDate', 'state', 'repairQuestion', 'logistics','receiveResult', 'orderType', 'completeDate', 'createdOutOrder','callRecord','dataAuthority','equipmentId','businessType','memberTypeName','pic','address','receiverWay'],
      sort: {
        id: -1
      },
      page: {
        page: this.data.page,
        pageSize: 10
      }
    }

    //按平台查询记录
    let appId=app.globalData.myAppId;
    if(appId!=3){
      //是否独立售后
      if(app.globalData.afterSaleSelf){
        dataObj.appId=app.globalData.myAppId;
      }else{
        dataObj.appId=[2,3,null];
      }
    }else{
        dataObj.appId=[2,3,null];
    }

    //单个设备的记录
    if(this.data.paramObj.equipmentId){
      dataObj.equipmentId=this.data.paramObj.equipmentId;
    }

    //设备编码
    if(this.data.searchValue){
      dataObj.equipmentNo='%' +this.data.searchValue+ '%';
    }

    //筛选状态
    if(this.data.valueState!=-1){
      dataObj.state=this.data.valueState;
    }

    //接单人
    if(this.data.valueReceive==1){
      dataObj['receiver.id']=this.data.user.id;
    }

    let param = {
      isAuth: true,
      className: 'afterSaleConsumableOrder',
      data: dataObj
    }

    CommonService.goFindList(param).then(res => {
      Toast.clear();
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;

        result.forEach(item => {
          //状态
          switch(item.state){
            case 0:
              item.stateWord='未接待';
              item.stateClass='c-1';
              break;
            case 1:
              item.stateWord='已完成';
              item.stateClass='c-2';
              break;
            case 2:
              item.stateWord='已接待';
              item.stateClass='c-3';
              break;
          }

          //业务类型
          if(item.businessType){
            switch(item.businessType){
              case 1:
                item.self_businessType='销售';
                break;
              case 2:
                item.self_businessType='租赁-授信';
                break;
              case 3:
                item.self_businessType='租赁-非授信';
                break;
              case 4:
                item.self_businessType='试机';
                break;
              case 5:
                item.self_businessType='存量改造';
                break;
            }
          }

          //耗材
          if(item.logistics && item.logistics.length){
            let arr=item.logistics;
            let self_partName=[];
            for(let i=0;i<arr.length;i++){
              if(arr[i].parts && arr[i].parts.length){
                arr[i].parts.forEach(item2 => {
                  self_partName.push(item2.part.name);
                });
              }
            }
            item.self_partName=self_partName;
          }
        });

        console.log('耗材工单列表');
        console.log(result);

        this.setData({
          list: this.data.list.concat(result)
        })
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
    })
  },

  //选择状态
  onChangeState({detail}) {
    this.setData({
      valueState: detail
    })
    this.refreshListAndPage();
  },

  //选择接单人
  onChangeReceive({detail}) {
    this.setData({
      valueReceive: detail
    })
    this.refreshListAndPage();
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.value
    })
  },

  //点击搜索
  onSearch(){
    this.refreshListAndPage();
  },

  //添加报修
  goToAdd(){
    let obj={
      repairType: 217,
      equipmentId: this.data.paramObj.equipmentId
    }

    wx.navigateTo({
			url: "/pages/repairAdd/repairAdd?paramObj="+JSON.stringify(obj)
		})
  },

  //详情
  goToLook(e){
    let detail=e.currentTarget.dataset.detail;

    let obj={
      repairId: detail.id,
      equipmentNo: detail.equipmentNo
    }

    wx.navigateTo({
			url: "/packageA/pages/consumableDetail/consumableDetail?paramObj="+JSON.stringify(obj)
		})
  },

  //接待
  onReceive(e){
    Dialog.confirm({
      title: '确定接单吗',
      confirmButtonText:'确定',
      cancelButtonText:'取消'
    }).then(() => {
      let detail=e.currentTarget.dataset.detail;
      let user=this.data.user;

      let param={
        className:'afterSaleConsumableOrder',
        data:{
          id: detail.id,
          state: 2,
          receiverDate: util.timeFormat(new Date()),
          receiver: {
            id: user.id,
            name: user.userName,
            phone: user.personalPhone,
            code: ''
          }
        }
      }

      CommonService.goSave(param).then(res=>{
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('成功');
          setTimeout(() => {
            this.refreshListAndPage();
          }, 1000);
        }else{
          Toast.fail('操作失败');
        }
      }).catch((error) => {
        Toast.fail('操作失败');
      })

    }).catch(() => {
    });
  },

  //跳转编辑(接待信息)
  goToEdit(e){
    let detail=e.currentTarget.dataset.detail;

    let obj={
      id: detail.id
    }

    wx.navigateTo({
			url: "/packageA/pages/consumableEdit/consumableEdit?paramObj="+JSON.stringify(obj)
		})
  },

  //跳转物流
  goToLogistics(e){
    let detail=e.currentTarget.dataset.detail;

    let obj={
      repairId: detail.id,
      equipmentNo: detail.equipmentNo
    }

    wx.navigateTo({
			url: "/packageA/pages/consumableLogistics/consumableLogistics?paramObj="+JSON.stringify(obj)
		})
  },

  //完成
  onClose(e){
    let detail=e.currentTarget.dataset.detail;

    //接待信息必填
    if(detail.receiverWay && detail.receiveResult){
      //物流必填
      if(detail.receiverWay.id!=225){
        if(detail.logistics && detail.logistics.length){
        }else{
          Toast.fail('请添加物流信息');
          return;
        }
      }
    }else{
      Toast.fail('接待信息不完整');
      return;
    }

    Dialog.confirm({
      title: '确定完成当前工单吗',
      message:'状态将更新为已完成',
      confirmButtonText:'完成',
      cancelButtonText:'取消'
    }).then(() => {
      let param={
        className:'afterSaleConsumableOrder',
        data:{
          id: detail.id,
          state: 1,
          completeDate: util.timeFormat(new Date())
        }
      }

      CommonService.goSave(param).then(res=>{
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('已完成');

          setTimeout(() => {
            this.refreshListAndPage();
          }, 1000);
        }else{
          Toast.fail('操作失败，请联系管理员');
        }
      }).catch((error) => {
        Toast.fail('操作失败，请联系管理员');
      })

    }).catch(() => {
    });
  },

  //删除
  onDelete(e){
    Dialog.confirm({
      title: '确定删除当前工单吗',
      confirmButtonText:'确定',
      cancelButtonText:'不删除了'
    }).then(() => {
      let detail=e.currentTarget.dataset.detail;

      let param={
        className:"afterSaleConsumableOrder",
        data:{
          id: detail.id
        }
      }

      CommonService.goDelete(param).then(res=>{
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('已删除');

          setTimeout(() => {
            this.refreshListAndPage();
          }, 1000);
        }else{
          Toast.fail('操作失败，请联系管理员');
        }
      }).catch((error) => {
        Toast.fail('操作失败，请联系管理员');
      })

    }).catch(() => {
    });
  },

  //拨打电话
  onCall(e){
    let userName=this.data.user.userName;
    let detail=e.currentTarget.dataset.detail;

    //打电话
    wx.makePhoneCall({
      phoneNumber: detail.repairMan.phone
    })

    //保存点击记录
    let callRecord=[];
    if(detail.callRecord && detail.callRecord.length){
      callRecord=detail.callRecord;
    }
    callRecord.push({
      time: util.timeFormat(new Date()),
      name: userName
    });

    let param={
      className:'afterSaleConsumableOrder',
      data:{
        id: detail.id,
        callRecord: callRecord
      }
    }

    CommonService.goSave(param).then(res=>{
    }).catch((error) => {
    })
  },

  //转单
  onChangeType(e){
    Dialog.confirm({
      title: '确定将当前工单转为维修工单吗',
      confirmButtonText:'确定',
      cancelButtonText:'不转了'
    }).then(() => {
      let detail=e.currentTarget.dataset.detail;

      let param={
        id: detail.id,
        equipmentNo: detail.equipmentNo,
        equipmentId: detail.equipmentId,
        dataAuthority: detail.dataAuthority,
        appId: [app.globalData.myAppId],
        project: detail.project,
        businessType: detail.businessType,
        depart: detail.depart,
        memberTypeName: detail.memberTypeName,
        repairDate: util.timeFormat(detail.repairDate),
        repairMan: {
          name: detail.repairMan.name,
          phone: detail.repairMan.phone
        },
        repairQuestion: detail.repairQuestion,
        pic: detail.pic,
        address: detail.address,
        orderType: {
          id: 216,
          name: "维修工单"
        }
      }

      CommonService.changeToMaintain(param).then(res=>{
        if (res.statusCode == 200 && res.data.success == true){
          Dialog.confirm({
            title: '操作成功',
            confirmButtonText:'查看维修工单',
            cancelButtonText:'留在本页'
          }).then(() => {
            //跳转到售后记录
            wx.reLaunch({
              url: '/packageA/pages/repairList/repairList'
            })
          }).catch(() => {
            //刷新列表和页码
            this.refreshListAndPage();
          });

        }else{
          Toast.fail('操作失败，请联系管理员');
        }
      }).catch((error) => {
        Toast.fail('操作失败，请联系管理员');
      })

    }).catch(() => {
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})
